package net.lbtech.service;

import net.lbtech.server.SimpleChatServerHandler;
import net.lbtech.util.CommonUtil;
import net.lbtech.util.EhcacheHelper;
import net.lbtech.util.WeatherUtil;
import net.lbtech.util.WifiDataFormatUtil;
import net.lbtech.util.db.DbBuilder;
import net.lbtech.util.exception.GetIaqConfigException;
import net.lbtech.util.exception.WeatherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/5 0005.
 */
public class GetWeather {

    protected static Logger logger = LoggerFactory.getLogger(GetWeather.class);

    public static byte[] getWeather(byte[] data) throws WeatherException {
        String mac = getMacString(data);
        return getCityWeather(mac);
    }

    public static byte[] getCityWeather(String mac) throws WeatherException {
        byte[] weather = new byte[6];
        byte[] cityByte;
        byte[] date;
        //根据MAC查询地址
        try {
            String cityCode =  getStringObjectMap(mac);
            String cityName = EhcacheHelper.get("getCityCodeByName",cityCode).toString();
            cityByte = CommonUtil.IntToByteArray(cityCode);
            //根据地址查询天气情况
            HashMap<String,String> outWeather = WeatherUtil.getOutDoorWeather(cityName);

            weather[0] = (byte)Integer.valueOf(outWeather.get("weather")).intValue();
            if(Integer.valueOf(outWeather.get("temperature")).intValue()>0){
                weather[1] = 1;
            }
            weather[2] = (byte)Integer.valueOf(outWeather.get("temperature")).intValue();
            weather[3] = (byte)Integer.valueOf(outWeather.get("humidity")).intValue();
            weather[4] = (byte)Integer.valueOf(outWeather.get("pm25")).intValue();
            weather[5] = (byte)Integer.valueOf(outWeather.get("level")).intValue();

            date = WifiDataFormatUtil.cityWeather(weather,cityByte);
        } catch (WeatherException e) {
            e.printStackTrace();
            throw e;
        }
        return date;
    }


    //根据mac地址查询出在什么城市
    private static String getStringObjectMap(String mac) {
        Map<String, Object> map = DbBuilder.getFirstRowMap("select * from iaq_instrument_config where mac=?",mac);
        String city = map.get("city").toString();
        return city;
    }

    //拼接mac地址
    public static String getMacString(byte[] data){
        String mac = "";
        for (int i = 13; i < 18; i++) {
            mac=mac+ CommonUtil.toHex(data[i]);
        }
        System.out.println(mac);
        return mac;
    }

}
